<template>
  <ContentWrap title="业绩走势">
    <template #header>
      <el-row class="w-100%">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-radio-group v-model="dataType" @change="handleDataTypeChange" class="mr-10px">
            <el-radio-button v-for="(item, index) in dataTypes" :key="index" :value="item.type">
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
          <el-radio-group v-model="timeRangeType" @change="handleTimeRangeTypeChange">
            <el-radio-button v-for="[key, value] in timeRange.entries()" :key="key" :value="key">
              {{ value.name }}
            </el-radio-button>
          </el-radio-group>
        </el-col>
        <!-- <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
          <div class="flex">
            <el-radio-group v-model="timeRangeType" @change="handleTimeRangeTypeChange">
              <el-radio-button v-for="[key, value] in timeRange.entries()" :key="key" :value="key">
                {{ value.name }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </el-col> -->
      </el-row>
    </template>
    <!-- 折线图 -->
    <Echart :height="300" :options="eChartOptions" />
  </ContentWrap>
</template>
<script lang="ts" setup>
import dayjs, { Dayjs } from 'dayjs'
import { EChartsOption } from 'echarts'
import * as TradeStatisticsApi from '@/api/mall/statistics/trade'
import { fenToYuan } from '@/utils'
import { formatDate } from '@/utils/formatTime'

/** 交易量趋势 */
defineOptions({ name: 'TradeTrendCard' })

enum TimeRangeTypeEnum {
  DAY30 = 1,
  WEEK = 7,
  MONTH = 30,
  YEAR = 365
} // 日期类型
const timeRangeType = ref(TimeRangeTypeEnum.DAY30) // 日期快捷选择按钮, 默认30天
const loading = ref(true) // 加载中
const dataType = ref(0)
const dataTypes = [
  {
    label: '综合业绩',
    type: 0
  },
  {
    label: '消耗业绩',
    type: 1
  },
  {
    label: '划卡业绩',
    type: 2
  }
]
// 时间范围 Map
const timeRange = new Map()
  .set(TimeRangeTypeEnum.DAY30, {
    name: '30天',
    series: [
      { name: '旗舰店', type: 'line', data: [] },
      { name: '三桥店', type: 'line', data: [] }
    ]
  })
  .set(TimeRangeTypeEnum.WEEK, {
    name: '周',
    series: [
      { name: '旗舰店', type: 'line', data: [] },
      { name: '三桥店', type: 'line', data: [] }
    ]
  })
  .set(TimeRangeTypeEnum.MONTH, {
    name: '月',
    series: [
      { name: '旗舰店', type: 'line', data: [] },
      { name: '三桥店', type: 'line', data: [] }
    ]
  })
  .set(TimeRangeTypeEnum.YEAR, {
    name: '年',
    series: [
      { name: '旗舰店', type: 'line', data: [] },
      { name: '三桥店', type: 'line', data: [] }
    ]
  })
/** 图表配置 */
const eChartOptions = reactive<EChartsOption>({
  grid: {
    left: 20,
    right: 20,
    bottom: 20,
    top: 80,
    containLabel: true
  },
  legend: {
    bottom: 0,
    data: [],
    textStyle: {
      color: 'auto'
    }
  },
  series: [],
  toolbox: {
    feature: {
      // 数据区域缩放
      dataZoom: {
        yAxisIndex: false // Y轴不缩放
      },
      brush: {
        type: ['lineX', 'clear'] // 区域缩放按钮、还原按钮
      },
      saveAsImage: { show: true } // 保存为图片
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },

    padding: [5, 10]
  },
  xAxis: {
    type: 'category',
    inverse: true,
    boundaryGap: false,
    axisTick: {
      show: false
    },
    data: [],
    axisLabel: {
      formatter: (date: string) => {
        switch (timeRangeType.value) {
          case TimeRangeTypeEnum.DAY30:
            return formatDate(date, 'MM-DD')
          case TimeRangeTypeEnum.WEEK:
            let weekDay = formatDate(date, 'ddd')
            if (weekDay == '0') weekDay = '日'
            return '周' + weekDay
          case TimeRangeTypeEnum.MONTH:
            return formatDate(date, 'D')
          case TimeRangeTypeEnum.YEAR:
            return formatDate(date, 'M') + '月'
          default:
            return date
        }
      }
    }
  },
  yAxis: {
    axisTick: {
      show: false
    }
  }
}) as EChartsOption
const handleDataTypeChange = () => {}

/** 时间范围类型单选按钮选中 */
const handleTimeRangeTypeChange = async () => {
  // 设置时间范围
  let beginTime: Dayjs
  let endTime: Dayjs
  switch (timeRangeType.value) {
    case TimeRangeTypeEnum.WEEK:
      beginTime = dayjs().startOf('week')
      endTime = dayjs().endOf('week')
      break
    case TimeRangeTypeEnum.MONTH:
      beginTime = dayjs().startOf('month')
      endTime = dayjs().endOf('month')
      break
    case TimeRangeTypeEnum.YEAR:
      beginTime = dayjs().startOf('year')
      endTime = dayjs().endOf('year')
      break
    case TimeRangeTypeEnum.DAY30:
    default:
      beginTime = dayjs().subtract(30, 'day').startOf('d')
      endTime = dayjs().endOf('d')
      break
  }
  // 发送时间范围选中事件
  await getOrderCountTrendComparison(beginTime, endTime)
}

/** 查询订单数量趋势对照数据 */
const getOrderCountTrendComparison = async (
  beginTime: dayjs.ConfigType,
  endTime: dayjs.ConfigType
) => {
  loading.value = true
  // 查询数据
  const list = await TradeStatisticsApi.getOrderCountTrendComparison(
    timeRangeType.value,
    beginTime,
    endTime
  )
  // 处理数据 根据业绩 从高到低排序
  const dates: string[] = []
  const series = [...timeRange.get(timeRangeType.value).series]
  for (let item of list) {
    dates.push(item.value.date)

    series[0].data.push(fenToYuan(Math.floor(Math.random() * 10000))) // 旗舰店
    series[1].data.push(fenToYuan(Math.floor(Math.random() * 10000))) // 消耗业绩
  }
  eChartOptions.xAxis!['data'] = dates
  eChartOptions.series = series
  eChartOptions.legend!['data'] = series.map((item) => item.name)

  loading.value = false
}

/** 初始化 **/
onMounted(() => {
  handleTimeRangeTypeChange()
})
</script>
